﻿
Partial Class App_Listen
    Inherits MyUI.PageBaseApp

    Public CurrAccount As mDB.Account
    Protected WithEvents GroupPrivate As UI.GroupButton(Of LinkButton)

    Protected WithEvents PostWrite As App_Controls_PostWrite
    Protected WithEvents PrivateMessage As App_Controls_PrivateMessage
    Public LastId As Date

#Region "PAGE"


    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        CurrAccount = CurrUser.CurrAccount

        LastId = Utils.Conv.ToTimeStampDate(CurrUser.Session.Alert.LastViewID)


        Me.GroupPrivate = New UI.GroupButton(Of LinkButton)(Me.ViewState, "GROUP_PRIVATE", "bottone-private-a")
        Me.PostWrite = FC("PostWrite", Master)
        Me.PrivateMessage = FC("PrivateMessage", Master)
        'Me.UpPPrivateMessage = FC("UpPPrivateMessage", Master)
        'Me.UpPPost = FC("UpPPost", Master)

        'Me.Master.UpPPost 

        If Not Me.IsPostBack Then
            Me.GroupPrivate.SelectButton = Me.Rbt3
            SetDataPage()
        Else

        End If

    End Sub

    Private Sub SetDataPage()

        'SetListAccount()

        If CurrAccount IsNot Nothing Then

            'UI.Grid.Bind(Me.GridUsers, Nothing)
            'UI.Grid.Bind(Me.GridSharePosts, Nothing)
            'UI.Grid.Bind(Me.GridMessage, Nothing)
            'UI.Rep.Bind(Me.RptPrivate, Nothing)

            'Me.PnlPrivateOrder.Visible = False
            SetConsole()
            SetListHashtag()

            SetListMessage()

            SetListPrivate()
            SetListHashTagPost()


            'Select Case Me.gg.SelectValue
            '    Case 1
            '        SetListMessage()
            '    Case 2
            '        SetListSharePost()
            '    Case 3
            '        SetListPost()
            '    Case 4
            '        SetPrivate()
            'End Select

        End If

        'Me.UpPConversations.Update()

    End Sub

    Private Sub GetNewAlert()

        If dic.Count > 0 Then Exit Sub
        dic.Add(GloukDB.Alert.Type.MESSAGE, New Dictionary(Of String, Boolean))
        dic.Add(GloukDB.Alert.Type.PRIVATE_POST, New Dictionary(Of String, Boolean))

        Dim dt = CurrUser.View_Alert.
            Where("alert_id", ">", Utils.Conv.ToInt(CurrUser.Session.Alert.LastViewID)).
            Limit(100).
        ToList

        For Each d In dt
            Dim Data = MyApp.JSONDeserialize(Of String)(d.Alert_Data)
            If Not dic(d.Alert_Type_Id).ContainsKey(Data) Then
                dic(d.Alert_Type_Id).Add(Data, True)
            End If
        Next
    End Sub


#End Region
    Public dic As New Dictionary(Of mDB.Alert.Type, Dictionary(Of String, Boolean))
#Region "CONSOLE"

    Protected Sub BtnReload_UpPConsole_Click(sender As Object, e As EventArgs) Handles BtnReload_UpPConsole.Click

        SetDataPage()

    End Sub

    Private Sub SetConsole()

        'If CurrUser.Session.Listen.Box.Count  =0 Then
        'CurrUser.Session.Listen.Box = New List(Of Integer) From {1, 2}
        'End If

        UI.Controls.ClassSet(Me.BtnViewMessage, CurrUser.Session.Listen.Box.Contains(1), "bottone-mentions-a", "bottone-mentions")
        UI.Controls.ClassSet(Me.BtnViewPrivate, CurrUser.Session.Listen.Box.Contains(2), "bottone-message-a", "bottone-message")
        UI.Controls.ClassSet(Me.BtnViewHashTagPost, CurrUser.Session.Listen.Box.Contains(3), "bottone-hashtags-a", "bottone-hashtags")

        ''''''''''''''''

    End Sub
    Protected Sub BtnViewMessage_Click(sender As Object, e As EventArgs) Handles BtnViewMessage.Click

        Utils.List.ToggleInt(CurrUser.Session.Listen.Box, 1)

        If CurrUser.Session.Listen.Box.Count > 2 Then
            CurrUser.Session.Listen.Box.Remove(3)
            SetListHashTagPost()
        End If


        SetConsole()
        SetListMessage()

    End Sub

    Protected Sub BtnViewPrivate_Click(sender As Object, e As EventArgs) Handles BtnViewPrivate.Click

        Utils.List.ToggleInt(CurrUser.Session.Listen.Box, 2)

        If CurrUser.Session.Listen.Box.Count > 2 Then
            CurrUser.Session.Listen.Box.Remove(3)
            SetListHashTagPost()
        End If


        SetConsole()
        SetListPrivate()

    End Sub

    Protected Sub BtnViewHashTagPost_Click(sender As Object, e As EventArgs) Handles BtnViewHashTagPost.Click

        Utils.List.ToggleInt(CurrUser.Session.Listen.Box, 3)

        If CurrUser.Session.Listen.Box.Count > 2 Then
            CurrUser.Session.Listen.Box.Remove(2)
            SetListPrivate()
        End If


        SetConsole()
        SetListHashTagPost()

    End Sub

#End Region

#Region "MESSAGE"

    Dim DataPost As New List(Of mDB.Message_Post)           ' post totali
    Dim DataMesage As Dictionary(Of String, mDB.Message_Post) ' tutte le menzioni
    Protected Sub SetListMessage()
        Dim List = Me.ListMessage

        Me.PnlMessage.Visible = CurrUser.Session.Listen.Box.Contains(1)
        Me.PnlMessage.EnableViewState = Me.PnlMessage.Visible

        GetNewAlert()

        If Me.PnlMessage.Visible Then

            DataMesage = DB.TAB.Message_Post.
                BY.Message_Post.To_Account_Id(CurrAccount.Id).
                OrderBy("pubb_date desc").
                Limit(100).
            NotifyChanged(False).ToDictionary(Of String)("post_code")


            If DataMesage.Count > 0 Then

                'postclone = (From p In post Select p.Value).ToList

                Do Until DataMesage.Count = 0

                    Dim CurrPost = DataMesage.First.Value

                    Dim ct = 0
                    Do Until CurrPost.Reply_To_Post_Code = ""

                        If DataMesage.ContainsKey(CurrPost.Reply_To_Post_Code) Then
                            CurrPost = DataMesage(CurrPost.Reply_To_Post_Code)
                        Else
                            Dim TmpPost = DB.TAB.Message_Post.BY.Message_Post.Post_Code(CurrPost.Reply_To_Post_Code).NotifyChanged(False).ToObj

                            If TmpPost Is Nothing Then
                                CurrPost.Reply_To_Post_Code = ""
                            Else
                                CurrPost = TmpPost
                                DataMesage.Add(TmpPost.Post_Code, TmpPost)
                            End If
                        End If

                        ct += 1
                    Loop

                    AddPostToList(CurrPost, 0)

                Loop

                Dim AccountIds = DataPost.Select(Function(o) o.Account_Id).Distinct.ToList

                Dim Accs = DB.TAB.Account.REL.Account.Account_Add_Info.
                    Where("id", "IN", AccountIds).
                ToDataTable

                Dim Message = (From post In DataPost Join acc In Accs On post.Account_Id Equals CInt(acc("Id")) Select acc, post, post.Id).ToList


                '-------------------------------------------------------
                ' LAYOUT
                '-------------------------------------------------------

                Dim DataBind As List(Of Object) = UI.ListData.Bind(List, Message, {"id"})

                MyUI.Data.SetListStatusPost(CurrAccount, UI.ListData.GetRowsList(List), DataBind.Select(Function(o) o.post.Post_Code.ToString).ToList)
                MyUI.Data.SetListStatusAccount(CurrAccount, UI.ListData.GetRowsList(List), DataBind.Select(Function(o) o.acc("account_code").ToString).ToList)

                For Each gr In List.Items
                    Dim Data = DataBind(UI.ListDataItem.GetIndexData(gr))   '  dd(UI.ListDataItem.GetIndexData(gr))


                Next

            Else

                UI.ListData.Bind(List, Nothing)

            End If


            DB.ResetChanges()
        End If

        Me.UpPMessage.Update()

    End Sub
    Private Sub AddPostToList(currpost As mDB.Message_Post, lvl As Integer)

        currpost.PostLevel = lvl
        DataPost.Add(currpost)

        Dim cc = currpost.Post_Code

        DataMesage.Remove(currpost.Post_Code)

        Dim oo = DB.TAB.Message_Post.
            BY.Message_Post.Reply_To_Post_Code(cc).
            Where("Reply_To_Post_Code", "=", cc).
        ToList()

        For Each p In oo
            AddPostToList(p, lvl + 1)
        Next

    End Sub

    Protected Sub PostWrite_Send() Handles PostWrite.Send

        SetListMessage()

    End Sub
    Protected Sub ListMessage_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListMessage.ItemCommand
        Dim List As ListView = sender
        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        If Row IsNot Nothing Then

            Dim id = UI.ListDataItem.GetKey(e.CommandSource)
            Dim postMessage = DB.TAB.Message_Post.GetByPK(id)


            Dim tw = New MyApp.Network.Twitter(CurrAccount.GetOauth)

            Select Case e.CommandName
                Case "SHARE"

                    'MyApp.Task.Send.SendPost(CurrAccount, New mDB.Task_Post With {.Share_Post_Code = postMessage.Post_Code, .Post_Type_Id = mDB.Task_Post.Type.SHARE})
                    CurrAccount.AddPostShare(postMessage.Post_Code)
                    MyUI.Data.SetRowSharedPost(Row, True)

                Case "UNSHARE"
                    'MyApp.Task.Send.RemovePost(CurrAccount, postMessage.Post_Code, GloukDB.Task_Post.Type.SHARE)
                    CurrAccount.RemoveSharePost(postMessage.Post_Code)
                    MyUI.Data.SetRowSharedPost(Row, False)

                Case "OPEN_PRIVATE"

                    Me.PrivateMessage.ToAccountId = postMessage.Account_Id
                    Me.Master.UpPPrivateMessage.Update()




                Case "REPLY"

                    'Dim PostWriteMessage = UI.ListDataItem.GetControl(Of ASP.app_controls_postwrite_ascx)(Row, "PostWriteMessage")
                    'PostWriteMessage.PostText = SF("@{0} ", postMessage.Account.Username)
                    'PostWriteMessage.Title = SF("Reply to @{0}", postMessage.Account.Username)
                    'PostWriteMessage.ReplyPostCode = postMessage.Post_Code
                    'PostWriteMessage.Visible = True

                    '-------------------------------
                    'Dim PostWrite = FC(Of ASP.app_controls_postwrite_ascx)("PostWrite", Master)  ' UI.Controls.FindControl(Of ASP.app_controls_postwrite_ascx)("PostWrite", Master.Controls)
                    Me.PostWrite.PostText = SF("@{0} ", postMessage.Account.Username)
                    Me.PostWrite.Title = SF("Reply to @{0}", postMessage.Account.Username)
                    Me.PostWrite.ReplyPostCode = postMessage.Post_Code
                    Me.PostWrite.SetDataPage()
                    Me.Master.UpPPost.Update()

                    'FC(Of UpdatePanel)("UpPPost", Master).Update()
                    'Me.UpPPost.Update()

                Case "ADD_FAVORITE"
                    'tw.AddFavoritePost(CurrAccount, postMessage.Post_Code)
                    CurrAccount.AddFavoritePost(postMessage.Post_Code)
                    MyUI.Data.SetRowFavoritePost(Row, True)


                Case "REMOVE_FAVORITE"
                    CurrAccount.RemoveFavoritePost(postMessage.Post_Code)
                    MyUI.Data.SetRowFavoritePost(Row, False)
                    'tw.RemoveFavoritePost(CurrAccount, postMessage.Post_Code)

                Case "FOLLOW"

                    tw.FollowAccont(CurrAccount, postMessage.Account.Account_Code)
                    Me.SetListMessage()

                Case "UNFOLLOW"

                    tw.UnFollowAccont(CurrAccount, postMessage.Account.Account_Code)
                    Me.SetListMessage()

                    'MyUI.Data.SetListFriendAccount(UI.ListData.GetRowsList(List), postMessage.Account.Account_Code, e.CommandName = "FOLLOW")
                    'MyUI.Data.SetListStatusAccount(CurrAccount, UI.ListData.GetRowsList(g))
                    'Me.UpPMessage.Update()


            End Select

        End If
    End Sub


#End Region

#Region "PRIVATE"

    Protected Sub SetListPrivate()
        Dim List = Me.ListPrivate

        Me.PnlPrivate.Visible = CurrUser.Session.Listen.Box.Contains(2)
        Me.PnlPrivate.EnableViewState = Me.PnlPrivate.Visible

        GetNewAlert()

        If Me.PnlPrivate.Visible Then

            '-------------------------------------------------------
            ' QUERY
            '-------------------------------------------------------

            'Dim q = CurrAccount.Tab_Private_Post.
            '    REL.Private_Post.ToAccount.
            '    Join("Account_Add_Info", "account_id", "to_account.id").
            '    OrderBy("maxdata desc").
            '    GroupBy("to_account.id").
            '    SetSelect("to_account.*", "Account_Add_Info.*", "count(*) as totmess", "max(pubb_date) as maxdata").
            'Limit(100)

            Dim q = CurrAccount.Tab_Private_Post_Last.
                REL.Private_Post_Last.ToAccount.
                Join("Account_Add_Info", "account_id", "to_account.id").
                OrderBy("pubb_date desc").
                SetSelect("to_account.*", "Account_Add_Info.*", "private_post_last.post_count as totmess", "pubb_date as maxdata").
            Limit(100)

            Select Case Me.GroupPrivate.SelectValue
                Case "1"
                Case "2"
                    q.Where("is_sent", "=", 1)
                Case "3"
                    q.Where("is_sent", "=", 0)

            End Select

            Dim dt = q.ToDataTable

            'mette per primo un account

            'Dim rr = dt.Rows(1)
            'Dim newrr = dt.NewRow
            'newrr.ItemArray = rr.ItemArray
            'dt.Rows.InsertAt(newrr, 0)
            'dt.Rows.Remove(rr)

            '-------------------------------------------------------
            ' LAYOUT
            '-------------------------------------------------------

            Dim DataBind As List(Of Object) = UI.ListData.Bind(List, dt, {"account_id"})

            MyUI.Data.SetListStatusAccount(CurrAccount, UI.ListData.GetRowsList(List), DataBind.Select(Function(o) o("account_code").ToString).ToList)


        End If

        Me.UpPPrivate.Update()

        'UI.Rep.Bind(g, q.ToDataTable)

    End Sub
    Protected Sub ListPrivate_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles ListPrivate.ItemCommand
        Dim List As ListView = sender
        Dim Row = UI.ListDataItem.GetRow(e.CommandSource)

        If Row IsNot Nothing Then

            Dim id = UI.ListDataItem.GetKey(e.CommandSource)
            Dim Account = DB.TAB.Account.GetByPK(id)

            Dim tw = New MyApp.Network.Twitter(CurrAccount.GetOauth)

            Select Case e.CommandName
                Case "OPEN_PRIVATE"

                    'Dim ListPrivateMess = UI.ListDataItem.GetControl(Of ListView)(Row, "ListPrivateMess")
                    'Dim PnlPrivateMess = UI.ListDataItem.GetPanel(Row, "PnlPrivateMess")
                    'Dim dt = DB.TAB.Private_Post.REL.Private_Post.ToAccount.BY.Private_Post.Account_Id(CurrAccount.Id, Account.Id).ToDataTable
                    'UI.ListData.Bind(ListPrivateMess, dt, {})
                    'PnlPrivateMess.Visible = True

                    ''$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
                    'Dim div_PrivateMess = UI.ListDataItem.GetControl(Of Control)(Row, "div_PrivateMess") 'itemPlaceholder
                    'Me.AddJScript(SF("$('#{0}').scrollTop($('#{0}')[0].scrollHeight);", div_PrivateMess.ClientID))
                    Me.PrivateMessage.ToAccountId = Account.Id
                    Me.PrivateMessage.SetDataPage()
                    Me.Master.UpPPrivateMessage.Update()

                Case "FOLLOW"

                    tw.FollowAccont(CurrAccount, Account.Account_Code)
                    MyUI.Data.SetRowFriendAccount(Row, True)

                Case "UNFOLLOW"

                    tw.UnFollowAccont(CurrAccount, Account.Account_Code)
                    MyUI.Data.SetRowFriendAccount(Row, False)


            End Select

        End If


    End Sub
    Protected Sub GroupPrivate_onselected(value As String) Handles GroupPrivate.Selected
        SetDataPage()
    End Sub

#End Region

#Region "HASH POST"

    'Private Sub DownloadQueryRealTime()


    '    If MyApp.Session.GetValueDate(MyApp.Session.key.QUERY_RT_LAST_UPDATE) < Now.AddSeconds(-120) Then
    '        Dim QueryIds = CurrAccount.Tab_Listen_Query.ToList(Of Integer)("query_id") '  CurrUser.Tab_Query.BY.Query.Real_Time(1).ToList(Of Integer)("id")

    '        If QueryIds.Count > 0 Then

    '            MyApp.Task.Update.QueryPostsUpdate(QueryIds, mDB.Query.UpdateModeType.REALTIME)

    '        End If

    '        MyApp.Session.SetValue(MyApp.Session.key.QUERY_RT_LAST_UPDATE, Now)

    '    End If


    'End Sub
    Protected Sub SetListHashtag()

        Dim hashtag = CurrAccount.Tab_Query_Listen.ToDataTable ' CurrAccount.Tab_Listen_Query.REL.Listen_Query.Query.SetSelect("query.*").ToDataTable

        UI.ListData.Bind(Me.ListHashtag, hashtag, {"id"})

    End Sub
    Protected Sub SetListHashTagPost()

        Me.PnlHashTagPost.Visible = CurrUser.Session.Listen.Box.Contains(3)
        Me.PnlHashTagPost.EnableViewState = Me.PnlHashTagPost.Visible

        If Me.PnlHashTagPost.Visible Then

            Dim g = Me.ListHashtagPost  ' Me.GridUsers

            'DB.TAB.Query.REL.Query.Listen_Query.BY.Listen_Query.Account_Id(CurrAccount.Id).ToList
            Dim dt = New mDB.Group_Query(
                CurrAccount.Tab_Query_Listen.
                Where("listen_disabled_view", "=", False).
                ToList
            ).GetLastPostFromQueries(100)

            UI.ListData.Bind(g, dt, {})

            'verifica connessioni
            'MyUI.Data.SetListStatusAccount(CurrAccount, UI.ListData.GetRowsList(g))



        End If

        Me.UpPHashTagPost.Update()

    End Sub

    Protected Sub Chk_Click(sender As Object, e As System.EventArgs)

        Dim id = UI.ListDataItem.GetKey(sender)
        Dim chk As CheckBox = sender
        Dim ql = CurrAccount.Tab_Listen_Query(id).ToObj

        ql.Listen_Disabled_View = Not chk.Checked
        DB.SubmitChanges()

        SetListHashTagPost()


    End Sub
#End Region


End Class
'Public Class GroupButton2(Of tres As {IButtonControl, WebControl})

'    Public Property CacheState As Object
'    Public Property group As String
'    Public Property cssactive As String


'    Private Buttons As New List(Of tres)
'    Private p As Page

'    Public ReadOnly Property SelectValue() As String
'        Get
'            Return Me.SelectButton.CommandArgument
'        End Get
'    End Property

'    Public Property Visible() As Boolean
'        Get
'            Return Me.Buttons(0).Visible
'        End Get
'        Set(ByVal value As Boolean)

'            For Each b In Me.Buttons
'                b.Visible = value
'            Next

'            ' newPropertyValue = value
'        End Set
'    End Property


'    Public Property SelectButtonID() As String
'        Get
'            Return Me.CacheState("_GROUP_" & Me.group)
'        End Get
'        Set(ByVal value As String)
'            Me.CacheState("_GROUP_" & Me.group) = value
'        End Set
'    End Property

'    Public Property SelectButton() As tres
'        Get
'            Return (From b As Object In Me.Buttons Where b.ID = Me.SelectButtonID).FirstOrDefault
'        End Get
'        Set(value As tres)
'            Me.SelectButtonID = DirectCast(value, Object).ID
'            SetDataButtonList()

'        End Set
'    End Property

'    Public Event Selected(value As String)


'    Sub New(cache As Object, group As String, cssactive As String)


'        Me.p = HttpContext.Current.CurrentHandler
'        Me.CacheState = cache
'        Me.group = group
'        Me.cssactive = cssactive

'        Buttons = UI.Controls.FindCommandControls(Of tres)(Me.p.Controls, group)



'        For Each b In Buttons
'            AddHandler b.Click, AddressOf BntExport_Click
'        Next

'        SetDataButtonList()

'    End Sub

'    Private Sub SetDataButtonList()

'        For Each b As Object In Buttons
'            UI.Controls.ClassSet(b, cssactive, b.ID = Me.SelectButtonID)
'        Next

'    End Sub


'    Protected Sub BntExport_Click(sender As Object, e As EventArgs)

'        Me.SelectButton = sender
'        RaiseEvent Selected(Me.SelectValue)

'    End Sub

'End Class







